package znbkCNtxl.CNTXL_YDJD;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.znbk.znbklibrary.base.BaseRecyclerAdapter;
import com.example.znbk.znbklibrary.base.BaseRecyclerViewHolder;
import com.example.znbk.znbklibrary.util.LancooUtils;
import com.example.znbk.znbklibrary.widget.CustomEditText;
import com.example.znbk.znbklibrary.widget.CustomTextViewToPicture;
import com.example.znbk.znbklibrary.widget.ScaleButton;
import com.lancoo.znbkxx.R;
import com.tt.CoreType;
import com.tt.QType;
import com.tt.SkEgnManager;
import com.tt.listener.OnRecordListener;
import com.tt.widget.AudioRecoderUtils;
import com.tt.widget.JSONTool;
import com.xujiaji.happybubble.BubbleDialog;
import com.xujiaji.happybubble.BubbleLayout;
import com.xujiaji.happybubble.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import znbkCNtxl.GetNtxlJson.CNtxlPaperEntity;

public class CNtxlYdjdAnswerAdapter extends BaseRecyclerAdapter {

    private Context context;
    private List<CNtxlPaperEntity> CNtxlPaperEntity;
    private int quesIndex = -1;
    private int childIndex= -1;
    private LayoutInflater inflater;

    public CNtxlYdjdAnswerAdapter(Context context, List<CNtxlPaperEntity> CNtxlPaperEntity, int quesIndex, int childIndex){
        this. context=context;
        this.CNtxlPaperEntity = CNtxlPaperEntity;
        this.quesIndex = quesIndex;
        this.childIndex = childIndex;
        inflater=LayoutInflater. from(context);
        getAnswerInfor();
    }

    private int SortIndex = -1;
    private void getAnswerInfor(){
        String TypeNo = CNtxlPaperEntity.get(quesIndex).getQuesFromTK().getTypeInfo().getTypeNo();
        if(TypeNo.equals("b")){

            int SubmitState = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
            int Size = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).getSubChildList().get(0).getSubChildItem().size();
            if(SubmitState==0) {
                for (int i = 0; i < Size; i++) {
                    CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).
                            getSubChildList().get(0).getSubChildItem().get(i).setStuAnswer("");
                }
            }

            SortIndex = CNtxlPaperEntity.get(quesIndex).getQuesFromTK().getChildList().
                    get(0).getSubChildList().get(0).getSubChildItem().get(childIndex).getSortIndex();
        }else if(TypeNo.equals("d")||TypeNo.equals("X")||TypeNo.equals("g")||TypeNo.equals("V")) {

            int SubmitState = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
            int Size = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().size();
            if(SubmitState==0) {
                for (int i = 0; i < Size; i++) {
                    CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(i).
                            getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("");
                }
            }

            SortIndex = CNtxlPaperEntity.get(quesIndex).getQuesFromTK().getChildList().
                    get(childIndex).getSubChildList().get(0).getSubChildItem().get(0).getSortIndex();
        }
    }

    @Override
    public int getItemCount() {
        return 1;
    }

    private TextView mTvChildQuesAsk;
    private TextView mTvChildPageInfor;
    private CustomEditText mCEdtYdjdText;
    private ScaleButton mSBtnClearText;
    private Button mBtnRecord;

    private LinearLayout mLlUnSubmitAnswerView;
    private LinearLayout mLlSubmitAnswerView;

    private CustomEditText mCEdtItemAnswer;
    private CustomEditText mCEdtStuAnswer;

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder baseRecyclerViewHolder, final int position) {

        //显示小题信息
        mTvChildQuesAsk = baseRecyclerViewHolder.getView(R.id.tv_childQuesAsk);
        mTvChildPageInfor = baseRecyclerViewHolder.getView(R.id.tv_childPageInfor);
        mTvChildQuesAsk.setVisibility(View.VISIBLE);
        new CustomTextViewToPicture(context,mTvChildQuesAsk,SortIndex+".");
        int childPageCount = CNtxlPaperEntity.get(quesIndex).getQuesFromTK().getTotalItemCount();
        mTvChildPageInfor.setText(Html.fromHtml(context.getResources().getString(R.string.child_paper_infor,(childIndex+1),childPageCount)));

        //初始化未作答作答界面View
        mLlUnSubmitAnswerView = baseRecyclerViewHolder.getView(R.id.ll_unSubmitAnswerView);
        //初始化已完成作答界面View
        mLlSubmitAnswerView = baseRecyclerViewHolder.getView(R.id.ll_submitAnswerView);
        //处理相应界面显示
        int SubmitState = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
        if(SubmitState==2){
            mLlUnSubmitAnswerView.setVisibility(View.GONE);
            mLlSubmitAnswerView.setVisibility(View.VISIBLE);

            mCEdtItemAnswer = baseRecyclerViewHolder.getView(R.id.cedt_itemAnswer);
            mCEdtItemAnswer.setFocusable(false);
            mCEdtStuAnswer = baseRecyclerViewHolder.getView(R.id.cedt_stuAnswer);
            mCEdtStuAnswer.setFocusable(false);

            String TypeNo = CNtxlPaperEntity.get(quesIndex).getQuesFromTK().getTypeInfo().getTypeNo();
            String ItemAnswer = "";
            String StuAnswer = "";
            double ScoreRate = 0;
            if(TypeNo.equals("b")){
                ItemAnswer = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).
                        getSubChildList().get(0).getSubChildItem().get(childIndex).getItemAnswer();
                StuAnswer = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).
                        getSubChildList().get(0).getSubChildItem().get(childIndex).getStuAnswer();
                ScoreRate = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).
                        getSubChildList().get(0).getSubChildItem().get(childIndex).getScoreRate();
            }else if(TypeNo.equals("d")||TypeNo.equals("X")||TypeNo.equals("g")||TypeNo.equals("V")) {
                ItemAnswer = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(childIndex).
                        getSubChildList().get(0).getSubChildItem().get(0).getItemAnswer();
                StuAnswer = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(childIndex).
                        getSubChildList().get(0).getSubChildItem().get(0).getStuAnswer();
                ScoreRate = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(childIndex).
                        getSubChildList().get(0).getSubChildItem().get(0).getScoreRate();
            }

            ItemAnswer = ItemAnswer.replaceAll("\\$","");

            String strScoreRate = "";
            if(ScoreRate==-1){
                strScoreRate = "暂时无法评测";
            }else{
                strScoreRate = LancooUtils.getPercentInstance(ScoreRate);
            }
            if(ScoreRate*100<60) {
                mCEdtItemAnswer.setText(Html.fromHtml(context.getResources().
                        getString(R.string.false_zgt_jd_answer_analysis, strScoreRate, ItemAnswer)));
            }else{
                mCEdtItemAnswer.setText(Html.fromHtml(context.getResources().
                        getString(R.string.true_zgt_jd_answer_analysis, strScoreRate, ItemAnswer)));
            }
            if(ItemAnswer.equals(StuAnswer)){
                mCEdtStuAnswer.setText(StuAnswer);
                mCEdtStuAnswer.setTextColor(Color.parseColor("#00b30d"));
            }else{
                if(StuAnswer.equals("")){
                    mCEdtStuAnswer.setText("未作答");
                    mCEdtStuAnswer.setTextColor(Color.parseColor("#ff0000"));
                }else{
                    mCEdtStuAnswer.setText(StuAnswer);
                    mCEdtStuAnswer.setTextColor(Color.parseColor("#ff0000"));
                }
            }

        }else{
            mLlUnSubmitAnswerView.setVisibility(View.VISIBLE);
            mLlSubmitAnswerView.setVisibility(View.GONE);

            //显示阅读简答输入内容
            mCEdtYdjdText = baseRecyclerViewHolder.getView(R.id.cedt_ydjdText);
            mCEdtYdjdText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    String StuAnswer = s.toString().trim();
                    int SubmitState = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
                    if(SubmitState!=2) {

                        String TypeNo = CNtxlPaperEntity.get(quesIndex).getQuesFromTK().getTypeInfo().getTypeNo();
                        if(TypeNo.equals("b")){
                            CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                                    get(0).getSubChildList().get(0).getSubChildItem().get(childIndex).setStuAnswer(StuAnswer);
                        }else if(TypeNo.equals("d")||TypeNo.equals("X")||TypeNo.equals("g")||TypeNo.equals("V")) {
                            CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                                    get(childIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer(StuAnswer);
                        }
                    }
                }
            });

            //设置清空按钮功能
            mSBtnClearText = baseRecyclerViewHolder.getView(R.id.sbtn_clearYdjdText);
            mSBtnClearText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mCEdtYdjdText.setText("");

                    String TypeNo = CNtxlPaperEntity.get(quesIndex).getQuesFromTK().getTypeInfo().getTypeNo();
                    if(TypeNo.equals("b")){
                        CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                                get(0).getSubChildList().get(0).getSubChildItem().get(childIndex).setStuAnswer("");
                    }else if(TypeNo.equals("d")||TypeNo.equals("X")||TypeNo.equals("g")||TypeNo.equals("V")) {
                        CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().
                                get(childIndex).getSubChildList().get(0).getSubChildItem().get(0).setStuAnswer("");
                    }
                }
            });


            //设置语音按钮
            mBtnRecord = baseRecyclerViewHolder.getView(R.id.btn_recordSpeakInput);
            mBtnRecord.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            if(!isMiRecording){
                                showRecordMiPopWindow(mBtnRecord);
                            }
                            return true;
                        case MotionEvent.ACTION_UP:
                        case MotionEvent.ACTION_CANCEL:
                            ObjectAnimator scaleXShow =  ObjectAnimator.ofFloat(bl,View.SCALE_X,1f,0f);
                            ObjectAnimator scaleYShow =  ObjectAnimator.ofFloat(bl,View.SCALE_Y,1f,0f);
                            ObjectAnimator translationYShow =  ObjectAnimator.ofFloat(bl,View.TRANSLATION_Y,0f,100f);
                            AnimatorSet setShow = new AnimatorSet();
                            setShow.playTogether(scaleXShow,scaleYShow,translationYShow);
                            setShow.setInterpolator(new DecelerateInterpolator());
                            setShow.setDuration(400);
                            setShow.addListener(new Animator.AnimatorListener() {
                                @Override
                                public void onAnimationStart(Animator animation) {

                                }

                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    SkEgnManager.getInstance(context).stopRecord();
                                    mRecoderUtils.stopRecord();
                                    mCurrentDialog.dismiss();
                                    mCurrentDialog = null;
                                }

                                @Override
                                public void onAnimationCancel(Animator animation) {

                                }

                                @Override
                                public void onAnimationRepeat(Animator animation) {

                                }
                            });
                            setShow.start();

                            return true;

                    }

                    return false;
                }

            });

        }


    }

    @Override
    public View getHolderView(ViewGroup parent, int position) {
        View view = inflater.inflate(R.layout.cntxl_adapter_item_answer_ydjd,parent, false);
        return view;
    }


    /********************************************************/
    private boolean isMiRecording = false;
    private AudioRecoderUtils mRecoderUtils;
    private String  mCoreType = CoreType.EN_ASR_REC;
    /*
     * 话咪录音操作
     * */
    OnRecordListener mOnRecordListener = new OnRecordListener() {
        @Override
        public void onRecordStart() {
            //开始录制
            isMiRecording = true;
            Log.e("17kouyuAAA", "=========开始录制111111=============>" );
        }
        @Override
        public void onRecording(int vad_status, int sound_intensity) {
            //录制中
//            Log.e("==onRecordingBB==","========vad_status==========="+vad_status);
//            Log.e("==onRecordingBB==","=========sound_intensity==========="+sound_intensity);
            int SubmitState = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getSubmitState();
            if(SubmitState==2){
                SkEgnManager.getInstance(context).stopRecord();
                mRecoderUtils.stopRecord();
            }
            showRecordVolumeSize(sound_intensity);
            if(vad_status==2){
                SkEgnManager.getInstance(context).stopRecord();
                mRecoderUtils.stopRecord();
            }
            Log.e("17kouyuAAA", "=========开始录制AAA======000000000======>"+vad_status );
        }
        @Override
        public void onRecordEnd(String result) {
            //录制结束
            try {
                final JSONObject json = new JSONObject(result);
                Log.e("17kouyuAAA", "返回json===>" + result);
                String speakResult = "";
                if(!getResult(result).equals("")) {
                    speakResult = getResult(result);
                }
                Log.e("==AFGAFGG==","========VVVVVVKKKKK》》==========="+speakResult);
                if(!speakResult.equals("")) {

                    String TypeNo = CNtxlPaperEntity.get(quesIndex).getQuesFromTK().getTypeInfo().getTypeNo();
                    String stuAnswer = "";
                    if(TypeNo.equals("b")){
                        stuAnswer = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).getSubChildList().get(0).
                                getSubChildItem().get(childIndex).getStuAnswer();
                        CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(0).getSubChildList().get(0).
                                getSubChildItem().get(childIndex).setStuAnswer(stuAnswer+speakResult+".");
                    }else if(TypeNo.equals("d")||TypeNo.equals("X")||TypeNo.equals("g")||TypeNo.equals("V")) {
                        stuAnswer = CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(childIndex).getSubChildList().get(0).
                                getSubChildItem().get(0).getStuAnswer();
                        CNtxlPaperEntity.get(quesIndex).getFavouriteAndNote().getChildList().get(childIndex).getSubChildList().get(0).
                                getSubChildItem().get(0).setStuAnswer(stuAnswer+speakResult+".");
                    }

                    mCEdtYdjdText.setText(stuAnswer+speakResult+".");

                    if(mCurrentDialog!=null){
                        SkEgnManager.getInstance(context).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
                        mRecoderUtils.startRecord();
                    }
                }
                isMiRecording = false;

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };


    private String getResult(String result) {

        String choiceSoundResult = "";
        StringBuilder keyValue = new StringBuilder();
        try{
            JSONObject returnObj = new JSONObject(result);
            JSONObject resultJSONObject = returnObj.getJSONObject("result");
            if(resultJSONObject.has("overall")){
                keyValue.append("总    分: " + resultJSONObject.getString("overall") + "\n");
            }
            Log.e("getResultAAAAA", "====返回json========答案=========>" + resultJSONObject.getString("recognition"));
            choiceSoundResult = resultJSONObject.getString("recognition");

        }catch (Exception e){
            e.printStackTrace();
        }
        keyValue.append("\n");
        keyValue.append(JSONTool.stringToJSON(result));

        return choiceSoundResult;
    }
    /************************************************************/
    private void showRecordVolumeSize(final int volumesize){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg =Message.obtain();
                msg.obj = volumesize;
                msg.what = 1;
                handler.sendMessage(msg);

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int VolumeSize = Integer.valueOf(msg.obj.toString());
                    if(VolumeSize>50){
                        VolumeSize=50;
                    }
                    int LevelSize = VolumeSize*200;
                    drawableVolume.setLevel(LevelSize);
                    break;
            }
        }
    };

    private ImageView mIvRecordVolume;
    private Drawable drawableVolume;
    private BubbleLayout bl = null;
    private BubbleDialog.Position mPosition = BubbleDialog.Position.TOP;
    private BubbleDialog mCurrentDialog = null;
    private void showRecordMiPopWindow(Button btn){
        bl = new BubbleLayout(context);
        bl.setBubbleColor(Color.BLACK);
        bl.setShadowColor(Color.GRAY);
        bl.setLookLength(Util.dpToPx(context, 10));
        bl.setLookWidth(Util.dpToPx(context, 10));
        bl.setBubbleRadius(0);

        ObjectAnimator scalexShow =  ObjectAnimator.ofFloat(bl,View.SCALE_X,0f,1.0f);
        ObjectAnimator scaleYShow =  ObjectAnimator.ofFloat(bl,View.SCALE_Y,0f,1.0f);
        ObjectAnimator translationYShow =  ObjectAnimator.ofFloat(bl,View.TRANSLATION_Y,100f,0f);
        AnimatorSet setShow = new AnimatorSet();
        setShow.playTogether(scalexShow,scaleYShow,translationYShow);
        setShow.setInterpolator(new DecelerateInterpolator());
        setShow.setDuration(300);
        setShow.start();

        /*
         * 开始作答
         * */
        mCurrentDialog = new BubbleDialog(context)
                .addContentView(LayoutInflater.from(context).inflate(R.layout.popwindow_record_mi, null))
                .setClickedView(btn)
                .setPosition(mPosition)
                .setBubbleLayout(bl)
                .setOffsetY(-20)
                .calBar(true)
                .softShowUp();
        mCurrentDialog.show();
        mIvRecordVolume = mCurrentDialog.findViewById(R.id.iv_RecordVolume);
        drawableVolume = mIvRecordVolume.getDrawable();

        mRecoderUtils = new AudioRecoderUtils();
        SkEgnManager.getInstance(context).startRecord(mCoreType, "", QType.QTYPE_EMPTY, mOnRecordListener);
        mRecoderUtils.startRecord();

    }

}
